package org.idea.spring.dependency.inject.aware;

import org.idea.spring.ioc.bean.Person;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * @Author linhao
 * @Date created in 11:11 上午 2021/4/23
 */
public class AwareInjectDemo implements BeanFactoryAware, ApplicationContextAware {

    private  BeanFactory beanFactory;

    private  ApplicationContext applicationContext;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(AwareInjectDemo.class);
        annotationConfigApplicationContext.refresh();
        AwareInjectDemo awareInjectDemo = annotationConfigApplicationContext.getBean(AwareInjectDemo.class);
        Person person = (Person) awareInjectDemo.beanFactory.getBean("person");
        System.out.println(annotationConfigApplicationContext.getBeanFactory() == awareInjectDemo.beanFactory);
        //当前的上下文和回调注入的上下文是同一个对象
        System.out.println(awareInjectDemo.applicationContext == annotationConfigApplicationContext);
        System.out.println(person);
        annotationConfigApplicationContext.close();
    }

    @Bean
    public Person person(){
        return new Person(1,"idea");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
       this.applicationContext = applicationContext;
    }
}
